<?php
/**
 * Created by PhpStorm.
 * User: 杨永安
 * Date: 2017/4/13
 * Time: 9:22
 */

namespace app\api\controller;

use app\api\model\UserAddressDefault;
use app\api\model\VerifyCode;


class My
{
    function index()
    {
        if (uid()) {
            $res['code'] = uid();
            $res['msg'] = session('user');
        } else {

            $res['code'] = -1;
            $res['msg'] = '账号找不到';
        }
        return json($res);
    }

    public function login()
    {
        $account = input('account');
        $password = input('password');


        $user = db('system_user')->where('mail', $account)->find();
        if (!$user) {
            $user = db('system_user')->where('username', $account)->find();
            if (!$user) {
                $user = db('system_user')->where('phone', $account)->find();
                if (!$user) {
                    $res['code'] = -1;
                    $res['msg'] = '账号找不到';
                    return json($res);
                }
            }
        }


        if (md5($password) == $user['password']) {
            session('user', $user);
            $res['code'] = 1;
            $res['msg'] = '欢迎回来';
        } else {
            $res['code'] = -2;
            $res['msg'] = '账号或者密码错误';
        }

        return json($res);
    }


    function logout()
    {
        session('user', null);
        $res['code'] = 1;

        return json($res);
    }

    function verifypwd()
    {
        $oldpwd = input('oldpwd');
        $pwd1 = input('newpwd1');
        $pwd2 = input('newpwd2');
        $info = db('system_user')->where('id', uid())->find();
        if ($pwd1 == '' || $pwd2 == '') {
            $res['code'] = -3;
            $res['msg'] = "请输入新密码！";
        } else {
            if (md5($oldpwd) != $info['password']) {
                $res['code'] = -1;
                $res['msg'] = "密码错误，请重新输入！";
            } else {
                if ($pwd1 != $pwd2) {
                    $res['code'] = 0;
                    $res['msg'] = '两次输入的新密码不一致，请重新输入！';
                } else {
                    $set = db('system_user')->where('id', uid())->update(['password' => md5($pwd2)]);
                    if ($set) {
                        $res['code'] = 1;
                        $res['msg'] = '密码修改成功！';
                    } else {
                        $res['code'] = -2;
                        $res['msg'] = "密码修改失败";
                    }
                }
            }
        }
        return json($res);
    }

    public function checkAccount($account)
    {
        $res = $this->verifyaccount($account);
        return json($res);
    }

    function verifyaccount($account)
    {

        $reg = '/^[\x{4E00}-\x{9FA5A}-Za-z][\x{4E00}-\x{9FA5A}-Za-z0-9]+$/u';

        if (preg_match($reg, $account)) {
            $user = db('system_user')->where('username', $account)->find();

            if ($user) {
                $res['msg'] = "用户名已经存在";
                $res['code'] = -1;
            } else {
                $res['msg'] = "用户名可用";
                $res['code'] = 1;
            }
        } else {
            $res['msg'] = "用户名为中文、字母或数字，且只能以汉字或字母开头,且长度不能小于2";
            $res['code'] = -2;
        }
        return $res;
    }

    public function getCode($account, $type)
    {

        $account = strtolower($account);

        $have = db('system_user')->where('mail', $account)->find();

        if ($have) {

            $res['msg'] = "邮件已经存在";
            $res['code'] = -11;
        } else {

            $verify_code = new VerifyCode();

            $code = rand(1000, 9999);
            $verify = $verify_code->where('account', $account)->where('type', $type)->find();

            if ($verify && time() < $verify['timeout']) {
                $code = $verify['code'];
            }


            $data['code'] = $code;
            $data['timeout'] = time() + 600;
            $data['account'] = $account;
            $data['type'] = $type;

            if ($verify) {
                $verify_code->where('account', $account)->update($data);
            } else {
                $verify_code->insert($data);
            }


            if ($type == 'email') {

                $title = '欢迎注册speedUp';
                $content = "您好,您的注册验证码是{$code},请输入完成注册!";

                if (sendEmail($account, $title, $content)) {

                    $res['msg'] = "邮件发送成功,请查收";
                    $res['code'] = 1;
                } else {
                    $res['msg'] = "邮件发送失败";
                    $res['code'] = -1;
                }

            } else if ($type == 'phone') {
                //TODO 手机
            } else {
                //TODO 其他
            }
        }

        return json($res);

    }

    function do_reg()
    {

        $username = input('username');
        $password = input('password');
        $email = strtolower(input('mailAddress'));
        $code = input('code');

        $verify = new VerifyCode;

        $checkaccount = $this->verifyaccount($username);

        if ($checkaccount['code'] > 0) {

            $verify_code = $verify->where('account', $email)->find();

            if ($verify_code) {

                if ($verify_code['code'] == $code && time() < $verify_code['timeout']) {

                    $data['username'] = $username;
                    $data['password'] = md5($password);
                    $data['mail'] = $email;

                    $reg = db('system_user')->insertGetId($data);

                    if ($reg) {


                        $user = db('system_user')->where('id', $reg)->find();

                        session('user', $user);

                        $res['code'] = 1;
                        $res['msg'] = "注册成功";
                    } else {

                        $res['code'] = -7;
                        $res['msg'] = "注册失败,错误码7";
                    }

                } else {

                    $res['code'] = -6;
                    $res['msg'] = "验证码超时或者错误";
                }

            } else {
                $res['code'] = -5;
                $res['msg'] = "验证码没找到";
            }

        } else {
            $res = $checkaccount;
        }

        return json($res);
    }


    function add_address($id = 0)
    {
        if (uid()) {

            $data['UserId'] = uid();
            $data['Name'] = input('name');
            $data['Phone'] = input('phone');
            $location = explode(',', input('location'));

            $data['Lon'] = $location[0];
            $data['Lat'] = $location[1];

            $data['City'] = input('city');
            $data['Address'] = input('address');

            if ($id) {
                $address = db('user_address')->where(['Id' => $id, 'UserId' => uid()])->find();
                if ($address) {
                    $user_address = db('user_address')->where('Id', $id)->update($data);
                } else {
                    $res['code'] = -2;
                    $res['msg'] = "修改";
                }
            } else {
                $user_address = db('user_address')->insertGetId($data);
            }

            if ($user_address) {

                $user_address_default = db('user_address_default')
                    ->where('UserId', uid())->find();
                if ($user_address_default) {
                    db('user_address_default')->where('UserId', uid())->update(['AddressId' => $user_address]);
                } else {
                    db('user_address_default')->insert(['UserId' => uid(), 'AddressId' => $user_address]);
                }

                $res['code'] = 1;
                $res['msg'] = "保存成功";
            } else {

                $res['code'] = -2;
                $res['msg'] = "设置失败";
            }

        } else {
            $res['code'] = -1;
            $res['msg'] = "请登录";
        }
        return json($res);

    }

    public function address()
    {
        if (uid()) {
            $res['code'] = 1;
            $res['msg'] = db('user_address')->where('UserId', uid())->order('Id', 'DESC')->select();

            $res['default'] = db('user_address_default')->where('UserId', uid())->value('AddressId');

        } else {
            $res['code'] = -1;
            $res['msg'] = "请登录";
        }
        return json($res);
    }

    function doAddress()
    {
        $id = input('id');
        $type = input('type');


        if ($type == 1) {
            $del = db('user_address')->where(['UserId' => uid(), "Id" => $id])->delete();
            if ($del) {
                $res['msg'] = "删除成功";
                $res['code'] = 1;
            } else {

                $res['msg'] = "删除失败";
                $res['code'] = -1;
            }
        } else {


            $user_address_default = db('user_address_default')
                ->where('UserId', uid())->find();
            if ($user_address_default) {
                $set = db('user_address_default')->where('UserId', uid())->update(['AddressId' => $id]);
            } else {
                $set = db('user_address_default')->insert(['UserId' => uid(), 'AddressId' => $id]);
            }


            if ($set) {
                $res['msg'] = "设置默认地址成功";
                $res['code'] = 2;
            } else {
                $res['msg'] = "设置默认地址失败";
                $res['code'] = -2;
            }

        }

        return json($res);
    }
}